package com.example.weight.greenSeasons.waterDeal;


import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class UseElectricityTable extends AppCompatActivity {
    //variable declare
    //now date
    private Date useElectricityDate = new Date(System.currentTimeMillis());

    //date formatter
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private String name, factory;
    //ui controller declare
    private TextView tv_use_electricity_date;
    private EditText et_water_reading, et_carbon_reading, et_remarks;

    private TitleBar titleBar;

    Calendar calendar= Calendar.getInstance(Locale.CHINA);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_use_electricity_table);

        tv_use_electricity_date = findViewById(R.id.use_electricity_date);
        et_water_reading = findViewById(R.id.et_water_reading);
        et_carbon_reading = findViewById(R.id.et_carbon_reading);
        et_remarks = findViewById(R.id.et_remarks);

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                UseElectricityTable.this.finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });

        tv_use_electricity_date.setText(simpleDateFormat.format(useElectricityDate));

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

//        runnable.run();

        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/sjqWaterProductionElectricityConsumption/findForm" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data = jsonObject.getJSONObject("data");
                            if (!data.isNull("id")) {
                                et_water_reading.setText(data.getString("wMeterReading"));
                                et_carbon_reading.setText(data.getString("cMeterReading"));
                                et_remarks.setText(data.getString("remarks"));
                                Toast.makeText(UseElectricityTable.this,
                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(UseElectricityTable.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }


    public void save(View view) {
        if (et_water_reading.getText().toString().equals("")) {
            Toast.makeText(this, "请填写水处理表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (et_carbon_reading.getText().toString().equals("")) {
            Toast.makeText(this, "请填写炭化表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/sjqWaterProductionElectricityConsumption/addForm";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
//                                    Toast.makeText(UseElectricityTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
//                                        String flag = jsonObject.getString("data");
//                                        Log.d("flag", String.valueOf(flag.equals("已保存过是否仍需保存")));

                                        if (code.startsWith("2"))
                                            Toast.makeText(UseElectricityTable.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
//                                        else if(flag.equals("已保存过是否仍需保存")){
//
//                                            new AlertDialog.Builder(UseElectricityTable.this)
//                                                    .setTitle("已保存过是否仍需保存？")
//                                                    .setCancelable(false)
//                                                    .setNegativeButton("取消", ((dialog, which) ->
//                                                            Toast.makeText(UseElectricityTable.this, "取消保存", Toast.LENGTH_SHORT).show()))
//                                                    .setPositiveButton("确定", (dialog, which) -> {
//                                                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
//                                                                new Response.Listener<String>() {
//                                                                    @Override
//                                                                    public void onResponse(String response) {
//                                                                        Log.d("jy", response);
//                                                                        try {
//                                                                            JSONObject jsonObject = new JSONObject(response);
//                                                                            String code = jsonObject.getString("code");
//                                                                            if (code.startsWith("2"))
//                                                                                Toast.makeText(UseElectricityTable.this,
//                                                                                        "保存成功", Toast.LENGTH_SHORT).show();
//                                                                            else{
//                                                                                Toast.makeText(UseElectricityTable.this,
//                                                                                        "保存失败", Toast.LENGTH_SHORT).show();
//                                                                            }
//                                                                        } catch (JSONException e) {
//                                                                            e.printStackTrace();
//                                                                        }
//                                                                    }
//                                                                }, new Response.ErrorListener() {
//                                                            @Override
//                                                            public void onErrorResponse(VolleyError error) {
//                                                                Toast.makeText(UseElectricityTable.this, "保存失败", Toast.LENGTH_SHORT).show();
//                                                                Log.d("jy", error.toString());
//                                                            }
//                                                        }) {
//                                                            @Override
//                                                            protected Map<String, String> getParams() throws AuthFailureError {
//                                                                Map<String, String> map=new HashMap<>();
//                                                                map.put("meter_reading_time", tv_current_time.getText().toString());
//                                                                map.put("w_meter_reading", et_water_reading.getText().toString());
//                                                                map.put("c_meter_reading", et_carbon_reading.getText().toString());
//                                                                map.put("reading_person",name);
//                                                                map.put("remarks", et_remarks.getText().toString());
//                                                                return map;
//                                                            }
//                                                        };
//                                                        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                                                                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//                                                        queue.add(stringRequest);
//                                                    })
//                                                    .show();
//                                        }
                                        else
                                            Toast.makeText(UseElectricityTable.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(UseElectricityTable.this,
                                    "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("meter_reading_time", tv_use_electricity_date.getText().toString());
                            map.put("w_meter_reading", et_water_reading.getText().toString());
                            map.put("c_meter_reading", et_carbon_reading.getText().toString());
                            map.put("reading_person",name);
                            map.put("remarks", et_remarks.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    //    选择日期
    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void chooseDate(View view) {

        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                tv_use_electricity_date.setText(new StringBuilder()
                        .append(year)
                        .append("-")
                        .append((month + 1) < 10 ? "0"
                                + (month + 1) : (month + 1))
                        .append("-")
                        .append((day < 10) ? "0" + day : day)
                        .append(" ")
                        .append(String.format("%02d",hourOfDay))
                        .append(":")
                        .append(String.format("%02d",minute)));
            },
                    HOUR, MINUTE, true).show();
        },
                YEAR, MONTH, DAY).show();
    }
}